<template>
  <px-dialog v-model="visible" width="640px" @close="closeDrawer" @open="openDrawer">
    <template #header>
      <h3 style="font-weight: bold">{{ drawerType === "edit" ? "编辑" : "新增" }}故障类型</h3>
    </template>
    <template #default>
      <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="140px">
        <px-form-item v-if="isParentSystem" label="上级故障类型名称" prop="parentId">
          <px-select v-model="formValue.parentId" placeholder="请选择上级故障类型名称">
            <px-option v-for="item in faultTypeList" :key="item.id" :label="item.faultTypeName" :value="item.id" />
          </px-select>
        </px-form-item>
        <px-form-item label="故障类型名称" prop="faultTypeName">
          <px-input v-model="formValue.faultTypeName" placeholder="请输入故障类型名称" maxlength="50" />
        </px-form-item>
        <px-form-item label="故障类型编码" prop="faultTypeCode">
          <px-input v-model="formValue.faultTypeCode" placeholder="请输入故障类型编码" maxlength="50" disabled />
        </px-form-item>
        <px-form-item label="备注" prop="remark">
          <px-input
            v-model="formValue.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="1000"
            clearable
          />
        </px-form-item>
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
import { saveFaultType, updateFaultType, getFaultTypeCode, getFirstFaultType } from "@/api/equip/maintain";
import { PxMessage } from "px-ui";
import { computed, ref, reactive, toRefs } from "vue";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);

const formRef = ref();
const props = defineProps(["visible", "drawerType", "detailData"]);
const visible = computed(() => props.visible);

const state = reactive<any>({
  formValue: {
    id: "",
    parentId: "",
    faultTypeName: "",
    faultTypeCode: "",
    remark: ""
  },
  faultTypeList: [],
  isParentSystem: false
});
const { formValue, faultTypeList, isParentSystem } = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  parentId: [
    {
      required: true,
      message: "上级故障类型名称不能为空",
      trigger: ["blur"]
    }
  ],
  faultTypeName: [
    {
      required: true,
      message: "故障类型名称不能为空",
      trigger: ["blur"]
    }
  ],
  faultTypeCode: [
    {
      required: true,
      message: "故障类型编码不能为空",
      trigger: ["blur"]
    }
  ]
}));
const openDrawer = async () => {
  if (props.drawerType === "add") {
    isParentSystem.value = false;
    const data = await getFaultTypeCode({});
    formValue.value.faultTypeName = "";
    formValue.value.faultTypeCode = data;
    formValue.value.remark = "";
    delete formValue.value.id;
    delete formValue.value.parentId;
  } else if (props.drawerType === "edit") {
    const { id, parentId, faultTypeName, faultTypeCode, remark } = props.detailData;
    formValue.value.id = id;
    formValue.value.faultTypeName = faultTypeName;
    formValue.value.faultTypeCode = faultTypeCode;
    formValue.value.remark = remark;
    if (parentId === 0) {
      isParentSystem.value = false;
      delete formValue.value.parentId;
    } else {
      const firstFaultType = await getFirstFaultType({});
      faultTypeList.value = firstFaultType || [];
      isParentSystem.value = true;
      formValue.value.parentId = parentId;
    }
  } else if (props.drawerType === "addChildren") {
    const firstFaultType = await getFirstFaultType({});
    faultTypeList.value = firstFaultType || [];
    isParentSystem.value = true;
    const data = await getFaultTypeCode({});
    const { id } = props.detailData;
    formValue.value.parentId = id;
    formValue.value.faultTypeName = "";
    formValue.value.faultTypeCode = data;
    formValue.value.remark = "";
    delete formValue.value.id;
  }
};

// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  emits("closeDrawer");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formValue.value));
      if (props.drawerType === "add") {
        await saveFaultType(params);
        PxMessage.success("新增成功");
        emits("closeDrawer");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        if (params.parentId !== 0) {
          const arr = faultTypeList.value.filter(item => {
            return item.id === formValue.value.parentId;
          });
          params.path = arr[0]?.path || "";
        }
        await updateFaultType(params);
        PxMessage.success("编辑成功");
        emits("closeDrawer");
        emits("queryTable");
      } else if (props.drawerType === "addChildren") {
        await saveFaultType(params);
        PxMessage.success("二级故障类型新增成功");
        emits("closeDrawer");
        emits("queryTable");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}
</style>
